package org.example.object;

/**
 * hashcode和equals方法一致性
 */
public class EqualsAndHashcodeDemo {
    private String name;
    private int age;

    public EqualsAndHashcodeDemo(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int hashCode() {
        int result = 17;
        result = 31 * result + name.hashCode();
        result = 31 * result + age;
        return result;
    }

    // 通常还需要覆盖equals方法来配合hashCode
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null || getClass() != obj.getClass())
            return false;
        EqualsAndHashcodeDemo other = (EqualsAndHashcodeDemo) obj;
        return age == other.age && name.equals(other.name);
    }
}
